<template>
  <div class="order-management">
    <div class="page-header">
      <h2>订单管理</h2>
      <div class="filters">
        <el-select v-model="statusFilter" placeholder="选择订单状态" clearable style="width: 200px; margin-right: 10px;">
          <el-option label="全部状态" value=""></el-option>
          <el-option label="已取消" :value="0"></el-option>
          <el-option label="待付款" :value="10"></el-option>
          <el-option label="待发货" :value="20"></el-option>
          <el-option label="待收货" :value="30"></el-option>
          <el-option label="已完成" :value="40"></el-option>
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索订单号"
          style="width: 250px; margin-right: 10px;"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="searchOrders">搜索</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>
    </div>

    <!-- 批量操作区域 -->
    <div class="batch-operations" v-if="selectedOrders.length > 0">
      <div class="selected-info">
        已选择 {{ selectedOrders.length }} 个订单
      </div>
      <div class="batch-buttons">
        <el-button 
          type="success" 
          @click="batchShipOrders"
          :disabled="!canBatchShip"
        >
          批量发货
        </el-button>
        <el-button 
          type="warning" 
          @click="batchCancelOrders"
          :disabled="!canBatchCancel"
        >
          批量取消
        </el-button>
        <el-button @click="clearSelection">清空选择</el-button>
      </div>
    </div>

    <el-table
      :data="orders"
      v-loading="loading"
      style="width: 100%"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="订单ID" width="100" />
      <el-table-column prop="orderNo" label="订单号" width="180" />
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="totalAmount" label="订单金额" width="120">
        <template #default="scope">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ scope.row.totalAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="paymentTime" label="支付时间" width="180">
        <template #default="scope">
          {{ scope.row.paymentTime ? formatDateTime(scope.row.paymentTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="updatedAt" label="更新时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.updatedAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="viewOrderDetail(scope.row)"
          >
            查看详情
          </el-button>
          <el-button
            v-if="scope.row.status === 10"
            type="warning"
            size="small"
            @click="updateOrderStatus(scope.row.orderNo, 0)"
          >
            取消订单
          </el-button>
          <el-button
            v-if="scope.row.status === 20"
            type="success"
            size="small"
            @click="updateOrderStatus(scope.row.orderNo, 30)"
          >
            发货
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :before-close="handleDetailClose"
    >
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单ID">{{ selectedOrder.id }}</el-descriptions-item>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ selectedOrder.userId }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">
            <span style="color: #f56c6c; font-weight: bold;">¥{{ selectedOrder.totalAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(selectedOrder.status)">{{ getStatusText(selectedOrder.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(selectedOrder.createdAt) }}</el-descriptions-item>
        </el-descriptions>

        <div class="order-items" style="margin-top: 20px;">
          <h4>商品详情</h4>
          <el-table :data="selectedOrder.items" border style="width: 100%">
            <el-table-column prop="productId" label="商品ID" width="100" />
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="mainImageUrl" label="商品图片" width="120">
              <template #default="scope">
                <el-image :src="scope.row.mainImageUrl" style="width: 80px; height: 80px" fit="contain" />
              </template>
            </el-table-column>
            <!-- 添加原价列 -->
            <el-table-column prop="originalPrice" label="原价" width="100">
              <template #default="scope">
                ¥{{ scope.row.originalPrice || scope.row.unitPrice }}
              </template>
            </el-table-column>
            <!-- 添加折扣列 -->
            <el-table-column prop="discount" label="折扣" width="80">
              <template #default="scope">
                <el-tag v-if="scope.row.discount && scope.row.discount < 1" type="danger" size="small">
                  {{ Math.round((1 - scope.row.discount) * 100) }}%
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="实付单价" width="120">
              <template #default="scope">
                ¥{{ scope.row.unitPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column label="小计" width="120">
              <template #default="scope">
                ¥{{ scope.row.unitPrice * scope.row.quantity }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量发货对话框 -->
    <el-dialog
      v-model="batchShipDialogVisible"
      title="批量发货"
      width="500px"
    >
      <el-form :model="batchShipForm" label-width="100px">
        <el-form-item label="物流公司">
          <el-input v-model="batchShipForm.shippingCarrier" placeholder="请输入物流公司" />
        </el-form-item>
        <el-form-item label="快递单号前缀">
          <el-input v-model="batchShipForm.trackingNumberPrefix" placeholder="请输入快递单号前缀" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="batchShipForm.remark" 
            type="textarea" 
            placeholder="发货备注（可选）"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div class="selected-orders-info">
        <p>将要发货的订单（{{ selectedOrders.length }}个）：</p>
        <div class="order-list">
          <el-tag 
            v-for="order in selectedOrders" 
            :key="order.id" 
            style="margin: 2px;"
          >
            {{ order.orderNo }}
          </el-tag>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchShipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBatchShip" :loading="batchShipping">
            确认发货
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { adminOrderApi } from '../../api/admin'

// 响应式数据
const loading = ref(false)
const orders = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const statusFilter = ref('')
const searchKeyword = ref('')

// 订单详情相关
const detailDialogVisible = ref(false)
const selectedOrder = ref(null)

// 批量操作相关
const selectedOrders = ref([])
const batchShipDialogVisible = ref(false)
const batchShipping = ref(false)
const batchShipForm = reactive({
  shippingCarrier: '',
  trackingNumberPrefix: '',
  remark: ''
})

// 计算属性：是否可以批量发货
const canBatchShip = computed(() => {
  return selectedOrders.value.every(order => order.status === 20)
})

// 计算属性：是否可以批量取消
const canBatchCancel = computed(() => {
  return selectedOrders.value.every(order => order.status === 10)
})

// 订单状态映射
const statusMap = {
  0: '已取消',
  10: '待付款',
  20: '待发货', 
  30: '待收货',
  40: '已完成'
}

// 获取状态标签类型
const getStatusType = (status: number) => {
  const typeMap = {
    0: 'danger',
    10: 'warning',
    20: 'primary',
    30: 'info', 
    40: 'success'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: number) => {
  return statusMap[status] || '未知状态'
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取订单列表
// 在fetchOrders方法中添加对商品详情的请求
const fetchOrders = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      status: statusFilter.value || undefined,
      orderNo: searchKeyword.value || undefined
    }
    const response = await adminOrderApi.getOrderList(params)
    console.log('API response:', response) // 添加调试日志
    orders.value = response.data.records.map(order => ({
      ...order,
      items: order.items || []
    }))
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取订单列表失败')
    console.error('获取订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索订单
const searchOrders = () => {
  currentPage.value = 1
  fetchOrders()
}

// 重置筛选条件
const resetFilters = () => {
  statusFilter.value = ''
  searchKeyword.value = ''
  currentPage.value = 1
  fetchOrders()
}

// 查看订单详情
const viewOrderDetail = async (order: any) => {
  selectedOrder.value = order
  detailDialogVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailDialogVisible.value = false
  selectedOrder.value = null
}

// 更新订单状态
const updateOrderStatus = async (orderNo: string, status: number) => {
  try {
    await adminOrderApi.updateOrderStatus(orderNo, { status })
    ElMessage.success('订单状态更新成功')
    fetchOrders()
  } catch (error) {
    ElMessage.error('更新订单状态失败')
    console.error('更新订单状态失败:', error)
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedOrders.value = selection
}

// 清空选择
const clearSelection = () => {
  selectedOrders.value = []
}

// 批量发货
const batchShipOrders = () => {
  if (!canBatchShip.value) {
    ElMessage.warning('只能对"待发货"状态的订单进行批量发货')
    return
  }
  batchShipDialogVisible.value = true
}

// 确认批量发货
const confirmBatchShip = async () => {
  if (!batchShipForm.shippingCarrier || !batchShipForm.trackingNumberPrefix) {
    ElMessage.warning('请填写物流公司和快递单号前缀')
    return
  }
  
  batchShipping.value = true
  try {
    const orderNos = selectedOrders.value.map(order => order.orderNo)
    await adminOrderApi.batchShipOrders({
      orderNos,
      shippingCarrier: batchShipForm.shippingCarrier,
      trackingNumberPrefix: batchShipForm.trackingNumberPrefix
    })
    ElMessage.success('批量发货成功')
    batchShipDialogVisible.value = false
    clearSelection()
    fetchOrders()
  } catch (error) {
    ElMessage.error('批量发货失败')
    console.error('批量发货失败:', error)
  } finally {
    batchShipping.value = false
  }
}

// 批量取消订单
const batchCancelOrders = async () => {
  if (!canBatchCancel.value) {
    ElMessage.warning('只能对"待付款"状态的订单进行批量取消')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要取消选中的 ${selectedOrders.value.length} 个订单吗？`,
      '批量取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const orderNos = selectedOrders.value.map(order => order.orderNo)
    await adminOrderApi.batchUpdateOrderStatus({
      orderNos,
      status: 0
    })
    ElMessage.success('批量取消成功')
    clearSelection()
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量取消失败')
      console.error('批量取消失败:', error)
    }
  }
}

// 分页相关
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchOrders()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchOrders()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.filters {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.order-detail {
  max-height: 600px;
  overflow-y: auto;
}

.order-items h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}

.batch-operations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.selected-info {
  font-weight: bold;
  color: #409eff;
}

.batch-buttons {
  display: flex;
  gap: 10px;
}

.selected-orders-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.order-list {
  max-height: 150px;
  overflow-y: auto;
  margin-top: 10px;
}
</style>